<template>
  <div style="background-color: #fff">
    <!-- 上传 -->
    <div>
      <div
        v-if="shoestatu"
        style="
          position: absolute;
          top: 0;
          width: 100%;
          height: 150px;
          opacity: 0;
          background: red;
          z-index: 111;
        "
      ></div>
      <van-field label="门店类型：" required>
        <van-dropdown-menu
          class="my_select"
          slot="input"
          style="height: 24px"
          active-color="#EE3F00"
        >
          <van-dropdown-item
            v-model="new_level"
            :options="types"
            @change="sowtype"
          />
        </van-dropdown-menu>
      </van-field>
      <van-field
        placeholder="其他类型店铺补充--如“建材门店”"
        v-model="otherpe"
        required
      >
        <span slot="label">补充类型：</span>
      </van-field>

      <van-field readonly required :border="false">
        <span slot="input">上传门店头（建议从手机相册选择图片）</span>
      </van-field>
      <!-- 类型 -->
      <!-- <van-field
        class="work_type"
        required
        @click="redirectTo"
        label="选择类型："
      >
        <v-select
          slot="input"
          style="width: 200px"
          :multiple="true"
          :selectable="selectWkTyped"
          :searchable="false"
          :close-on-select="false"
          :options-label="'label'"
          :options-value="'value'"
          v-model="wkTypeSelected"
          :options="workType"
          placeholder="只可选一种"
        ></v-select>
      </van-field> -->

      <div style="display: flex; width: 90%; margin: auto">
        <img
          :src="shoplogo"
          alt=""
          width="80px"
          height="80px"
          v-if="shoestatu"
        />
        <van-uploader
          v-if="!shoestatu"
          :max-count="1"
          v-model="filest"
          upload-text="上传门店头"
          style=""
          v-show="show_upload"
          :before-read="beforeR"
          :after-read="afterR"
          :before-delete="beforeD"
        />
      </div>
    </div>
    <div>
      <van-field readonly required :border="false">
        <span slot="input">上传身份证（建议从手机相册选择图片）</span>
      </van-field>
      <div style="display: flex; width: 90%; margin: auto">
        <img
          :src="CardBefore"
          alt=""
          width="80px"
          height="80px"
          v-if="shoestatu"
        />
        <van-uploader
          v-if="!shoestatu"
          :max-count="1"
          v-model="fileList"
          upload-text="身份证正面"
          style=""
          v-show="show_upload"
          :before-read="beforeRead"
          :after-read="afterRead"
          :before-delete="beforeDelete"
        />
        <img
          :src="CardAfter"
          alt=""
          width="80px"
          height="80px"
          v-if="shoestatu"
        />
        <van-uploader
          v-if="!shoestatu"
          :max-count="1"
          v-model="fileL"
          upload-text="身份证反面"
          style=""
          v-show="show_upload"
          :before-read="beforeReady"
          :after-read="afterReady"
          :before-delete="beforeDeletey"
        />
        <img
          :src="license"
          alt=""
          width="80px"
          height="80px"
          v-if="shoestatu"
        />
        <van-uploader
          v-if="!shoestatu"
          :max-count="1"
          v-model="fieL"
          upload-text="营业执照"
          style=""
          v-show="show_upload"
          :before-read="befor"
          :after-read="afte"
          :before-delete="beford"
        />
      </div>
    </div>

    <!--表单  -->
    <van-cell-group label-align="right">
      <van-field
        placeholder="请输入店铺名称"
        v-model="shopname"
        required
        :disabled="shoestatu"
      >
        <span slot="label">店铺名称：</span>
      </van-field>
      <van-field
        placeholder="请输入店长名称"
        v-model="shopent"
        required
        :disabled="shoestatu"
      >
        <span slot="label">
          <span>店</span><span style="margin: 0 6px"></span>
          <span>长</span> ：</span
        >
      </van-field>
      <van-field
        placeholder="请输入联系电话"
        v-model="shophone"
        type="number"
        required
        :disabled="shoestatu"
      >
        <span slot="label">联系电话：</span>
      </van-field>
      <!-- <van-field class="work_type" required>
        <span slot="label">服务类型：</span>
        <v-select
          slot="input"
          style="width: 90%"
          :multiple="true"
          :selectable="selectWkType"
          :searchable="false"
          :close-on-select="false"
          :options-label="'label'"
          :options-value="'value'"
          v-model="wkTypeSelected"
          :options="types"
          placeholder="只能选择一种类型"
        ></v-select>
      </van-field> -->
      <!--  -->

      <van-field
        label="所在城市："
        required
        @click="staterly(2)"
        v-if="!shoestatu"
      >
        <span slot="input">
          <span>{{
            province == '' ? '请选择所在城市' : province + city + areay
          }}</span>
          &#12288;
        </span>
      </van-field>
      <van-field
        label="所在城市："
        required
        v-if="shoestatu"
        :disabled="shoestatu"
      >
        <span slot="input">
          <span style="color: #32323373">{{
            province == '' ? '请选择所在城市' : province + city + areay
          }}</span>
          &#12288;
        </span>
      </van-field>
      <van-field
        placeholder="请输入具体位置"
        v-model="shoparea"
        required
        :disabled="shoestatu"
      >
        <span slot="label">具体位置：</span>
      </van-field>
      <van-field
        placeholder="请填写店铺简介：如主营产品、服务类型等"
        v-model="shoptext"
        rows="2"
        autosize
        type="textarea"
        maxlength="50"
        show-word-limit
        :disabled="shoestatu"
      >
        <span slot="label">店铺简介：</span>
      </van-field>
      <!-- 弹窗 -->
      <van-popup v-model="showstype" position="bottom"> </van-popup>
      <van-popup v-model="showcity" position="bottom">
        <van-area
          :area-list="areaList"
          :columns-num="3"
          @cancel="onCancel"
          @confirm="onConfirm"
        />
      </van-popup>
    </van-cell-group>

    <div style="padding: 0 16px; margin-top: 15px">
      <van-button
        v-if="!shoestatu"
        style="
          width: 100%;
          font-size: 18px;
          color: white;
          background: rgb(255, 170, 37);
        "
        @click="upcard()"
        >确认提交</van-button
      >
    </div>
  </div>
</template>

<script>
import {
  Uploader,
  Toast,
  Button,
  Checkbox,
  Field,
  Popup,
  Area,
  DropdownMenu,
  DropdownItem,
} from 'vant';
import lrz from 'lrz';
import { getLocalStorage } from '@/utils/local-storage';
import {
  storageUpload,
  Uploadcard,
  authInfo,
  qustores,
  shopadd,
  lianadd,
  byGroupId,
} from '@/api/api';
import areaList from '@/views/user/module-address-edit/area_all.json';
export default {
  name: 'openshop',
  data() {
    return {
      userId: Number(getLocalStorage('userId').userId),
      new_level: -1,
      otherpe: '',
      license: '',
      fileList: [],
      areaList: areaList,
      fileL: [],
      fieL: [],
      filest: [],
      wkTypeSelected: [],
      wkTypeSelete: '',
      wkType: [],
      images: [],
      types: [{ text: '请选择门店类型', value: -1 }],
      show_upload: true,
      showstype: false,
      showcity: false,
      shopname: '',
      shoparea: '',
      shopent: '',
      shophone: '',
      shopcity: '',
      typext: '',
      shoplogo: '',
      shoptext: '',
      CardBefore: '',
      CardAfter: '',
      province: '',
      city: '',
      areay: '',
      areaycode: '',
      citycode: '',
      provincoed: '',
      shoestatu: false,
      positionId: '',
      workType: [],
    };
  },
  created() {
    this.queryGoodShop();
    this.init();
    byGroupId({ groupId: 'SHOP_TYPE_LIANMENG' }).then((res) => {
      let list = res.data.data.list;
      let opiton;
      for (let i in list) {
        opiton = {
          text: list[i].itemName,
          value: parseInt(list[i].itemValue),
        };
        this.types.push(opiton);
      }
    });
  },
  methods: {
    sowtype(value) {
      // console.log(value, this.new_level);
    },
    // 状态选择
    queryGoodShop() {
      qustores({ userId: this.userId }).then((res) => {
        let shopdata = res.data.data;
        this.shoestatu = false;
        if (shopdata.tel != undefined) {
          Toast('提交成功，请上传产品');
          this.shoestatu = true;
        } else {
          this.shoestatu = false;
        }
        this.otherpe = shopdata.showTypeRemark;
        this.new_level = shopdata.shopType;
        this.license = shopdata.cer;
        this.shoptext = shopdata.intro;
        this.shopId = res.data.data.id;
        this.shopname = shopdata.shopName;
        this.shophone = shopdata.tel;
        this.shopent = shopdata.name;
        this.province = shopdata.province;
        this.city = shopdata.city;
        this.areay = shopdata.area;
        this.shoparea = shopdata.shopAddress;
        this.CardBefore = shopdata.sfzZ;
        this.CardAfter = shopdata.sfzF;
        this.shoplogo = shopdata.shopLogo;
      });
    },
    init() {
      authInfo().then((res) => {
        this.positionId = res.data.data.positionId;
      });
    },
    selectWkType(option) {
      if (this.wkTypeSelected.length >= 1) {
        // 修改选择数量
        Toast('最多只能选择1个');
        return false;
      } else {
        return true;
      }
      return true;
    },

    staterly(id) {
      if (id == 2) {
        this.showcity = true;
        return;
      }
      this.showstype = true;
    },

    onConfirm(value, index, item) {
      if (this.showstype) {
        this.typext = value;
        this.showstype = false;
        return;
      }
      if (this.showcity) {
        if (value[0].name == '全国地区') {
          this.province = '';
          this.city = '';
          this.areay = '';
          this.showcity = false;
          return;
        }
        this.province = value[0].name;
        this.city = value[1].name;
        this.areay = value[2].name;
        this.provincoed = value[0].name;
        this.citycode = value[1].name;
        this.areaycode = value[2].name;
        this.showcity = false;
        console.log(this.areaycode);
        return;
      }
    },

    onCancel() {
      this.showcity = false;
      this.showstype = false;
    },
    onChange(picker, value, index) {},

    // 提交
    upcard() {
      this.getworkpe();

      let rightPhone = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/);
      if (this.new_level == -1) {
        Toast('请选择服务类型');
        return;
      }
      if (this.shoplogo == '') {
        Toast('请上传门店头');
        return;
      }
      if (this.CardBefore == '') {
        Toast('请上传身份证正面');
        return;
      }
      if (this.CardAfter == '') {
        Toast('请上传身份证背面');
        return;
      }
      if (this.shoplogo == '') {
        Toast('请上传门店头');
        return;
      }
      if (this.shopname == '') {
        Toast('请输入店铺名称');
        return;
      }
      if (this.shopent == '') {
        Toast('请输入店长名称');
        return;
      }
      if (!rightPhone.test(this.shophone)) {
        Toast('请输入正确的联系电话');
        return;
      }
      if (this.province == '') {
        Toast('请选择城市');
        return;
      }
      if (this.license == '') {
        Toast('请上传营业执照');
        return;
      }
      if (this.shoparea == '') {
        Toast('请输入具体位置');
        return;
      }
      if (
        this.positioid == 6001 ||
        this.positioid == 2001 ||
        this.positioid == 6004
      ) {
        lianadd({
          userId: this.userId,
          cer: this.license,
          shopLogo: this.shoplogo,
          tel: this.shophone,
          mobile: this.shophone,
          name: this.shopent,
          shopName: this.shopname,
          shopAddress: this.shoparea,
          intro: this.shoptext,
          area: this.areaycode,
          province: this.provincoed,
          city: this.citycode,
          sfzF: this.CardAfter,
          sfzZ: this.CardBefore,
          shopType: this.new_level,
          showTypeRemark: this.otherpe,
        })
          .then((res) => {
            this.queryGoodShop();
            setTimeout(Toast('提交成功，请上传产品'), 3000);
            this.$router.go(-1);
            // console.log(res.data, 5);
          })
          .catch((err) => {
            Toast(err.data.errmsg);
          });
      } else {
        shopadd({
          userId: this.userId,
          cer: this.license,
          shopLogo: this.shoplogo,
          tel: this.shophone,
          mobile: this.shophone,
          name: this.shopent,
          shopName: this.shopname,
          shopAddress: this.shoparea,
          intro: this.shoptext,
          province: this.province,
          city: this.city,
          area: this.areay,
          sfzF: this.CardAfter,
          sfzZ: this.CardBefore,
          shopType: this.new_level,
          showTypeRemark: this.otherpe,
        })
          .then((res) => {
            this.queryGoodShop();
            Toast('提交成功，请等待审核！');
            this.$router.go(-1);
            // console.log(res.data, 5);
          })
          .catch((err) => {
            Toast(err.data.errmsg);
          });
      }
    },
    getworkpe() {
      // this.wkType = new Array();
      for (let i = 0; i < this.wkTypeSelected.length; i++) {
        this.wkTypeSelete = Number(this.wkTypeSelected[i].value);
      }
    },

    // 营业执照
    befor(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afte(file) {
      //文件读取完成后的回调函数
      let that = this;
      file.status = 'uploading';
      file.message = '上传中...';
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);

        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.license = res.data.data.url;
            file.status = 'done';
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.license = res.data.data.url;
                file.status = 'done';
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            file.status = 'failed';
            file.message = '压缩失败';
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beford(file, detail) {
      this.images.splice(detail.index, 1);
      this.license = '';
      return true;
    },

    // 图片上传
    uploadImg() {
      if (this.fileList.length > 1) return Toast('请上传2张以内的图片');
      this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
      if (this.fileL.length > 1) return Toast('请上传2张以内的图片');
      this.show_upload = true;
      document.querySelector('.van-uploader__input').click();
    },
    beforeRead(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterRead(file) {
      //文件读取完成后的回调函数
      let that = this;
      file.status = 'uploading';
      file.message = '上传中...';
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.CardBefore = res.data.data.url;
            file.status = 'done';
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.CardBefore = res.data.data.url;
                file.status = 'done';
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            file.status = 'failed';
            file.message = '压缩失败';
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeDelete(file, detail) {
      this.images.splice(detail.index, 1);
      this.CardBefore = '';
      return true;
    },

    // 背面

    beforeReady(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterReady(file) {
      //文件读取完成后的回调函数
      let that = this;
      file.status = 'uploading';
      file.message = '上传中...';
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.CardAfter = res.data.data.url;
            file.status = 'done';
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.CardAfter = res.data.data.url;
                file.status = 'done';
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            file.status = 'failed';
            file.message = '压缩失败';
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeDeletey(file, detail) {
      this.images.splice(detail.index, 1);
      this.CardAfter = '';
      return true;
    },

    // 门头
    beforeR(file) {
      //上传之前校验
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        Toast('只允许上传jpg/png格式的图片！');
        return false;
      }
      if (file.size >= 5242880) {
        Toast('只允许上传小于5MB的图片！');
        return false;
      }
      return true;
    },
    async afterR(file) {
      //文件读取完成后的回调函数
      let that = this;
      file.status = 'uploading';
      file.message = '上传中...';
      if (file.size < 1048576) {
        //图片小于1MB不压缩
        //成功时执行
        const formData = new FormData();
        formData.append('file', file.file);
        storageUpload(formData)
          .then((res) => {
            that.images.push(res.data.data.url);
            that.shoplogo = res.data.data.url;
            file.status = 'done';
          })
          .catch(() => {
            file.status = 'failed';
            file.message = '上传失败';
          });
      } else {
        lrz(file.file, {
          //width : 300
          quality: 0.7, //自定义使用压缩方式
        })
          .then(function (rst) {
            //成功时执行
            storageUpload(rst.formData)
              .then((res) => {
                that.images.push(res.data.data.url);
                that.shoplogo = res.data.data.url;
                file.status = 'done';
              })
              .catch(() => {
                file.status = 'failed';
                file.message = '上传失败';
              });
          })
          .catch(function (error) {
            //失败时执行
            file.status = 'failed';
            file.message = '上传失败';
          })
          .always(function () {
            //不管成功或失败，都会执行
          });
      }
    },
    beforeD(file, detail) {
      this.images.splice(detail.index, 1);
      this.shoplogo = '';
      return true;
    },
  },
  components: {
    [Checkbox.name]: Checkbox,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Toast.name]: Toast,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Area.name]: Area,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
  },
};
</script>
<style lang="scss" scoped>
/deep/.vs__dropdown-toggle {
  border: none !important;
}
/deep/.van-dropdown-menu__bar {
  height: 24px;
  box-shadow: none;
}
/deep/.van-dropdown-menu__title {
  padding-left: 0;
}
</style>
